<?php

namespace common\models;

use Yii;
use common\models\User;

/**
 * This is the model class for table "recharge".
 *
 * @property string $id
 * @property integer $user_id
 * @property string $relation_id
 * @property string $money
 * @property string $poundage
 * @property integer $status
 * @property string $bank_serial_no
 * @property integer $pay_type
 * @property string $create_time
 * @property string $update_time
 */
class Recharge extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'recharge';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'relation_id', 'money', 'poundage', 'bank_serial_no', 'create_time', 'update_time'], 'required'],
            [['id', 'user_id', 'status', 'pay_type'], 'integer'],
            [['money', 'poundage'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['relation_id'], 'string', 'max' => 50],
            [['bank_serial_no'], 'string', 'max' => 100],
        ];
    }
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_username' => '用户账号',
            'user_id' => '用户编号',
            'relation_id' => '相关id',
            'money' => '金额',
            'poundage' => '手续费',
            'status' => '状态',//'1充值中 2成功 3失败',
            'bank_serial_no' => '银行流水号',
            'pay_type' => '支付类型',//'1网银 21 微信服务号 31支付宝',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
        ];
    }

    public static function itemAlias ($type, $code = NULL)
    {
        $_items = [            
            'status' => [
                //''  =>'支付状态',
                '1' => "充值中",              
                '2' => "成功",
                '3' => "失败",
            ],
            'pay_type' => [
                //''  =>'配送状态',
                '1' => "网银",              
                '21' => "微信服务号",
                '31' => "支付宝",
            ],
        ];

        if (isset($code))
            return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
        else
            return isset($_items[$type]) ? $_items[$type] : false;
    }

    /*
    * 保存前执行的操作
    */
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            //是否是新添加
            if($this->isNewRecord) {
                
                $this->status = 1;
                $this->pay_type = 1;
                $this->create_time = date("Y-m-d H:i:s", time());
            }else{
                $this->update_time = date("Y-m-d H:i:s", time());
            }
            return true;
        } else {
            return false;
        }
    }
}
